package com.sth.test6;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.sth.domain.ItemResultEntity;
import com.sth.domain.TestResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author: sitianhong
 * @Description:
 * @Since: create in 2021/11/29 0029 15:58
 */
@Slf4j
public class Processor6 {
    static List<TestResultEntity> allList = new ArrayList<>();
    static List<String> keywordList = Arrays.asList("DDR_VDDE", "IO_3V3", "RTC_3V", "PEST_3V3", "VDD_RSM", "ACPI_3V3", "PLL_CORE_VDD", "PLL_DDR_VDD", "PLL_PIX0_VDD", "PLL_PIX1_VDD", "PLL_SOC_VDD",
                                                    "GMAC_VDDE", "USB_A3V3", "DDR_VREF", "PEST_1V1", "VDD PASSED");
    static List<String> keywordList2 = Arrays.asList("DDR_VDDE", "IO_3V3", "RTC_3V", "PEST_3V3", "VDD_RSM", "ACPI_3V3", "PLL_CORE_VDD", "PLL_DDR_VDD", "PLL_PIX0_VDD", "PLL_PIX1_VDD", "PLL_SOC_VDD",
                                                     "GMAC_VDDE", "USB_A3V3", "DDR_VREF", "PEST_1V1");

    static String unitRule = "\\d+";
    static String valueRule = "[a-zA-Z]";

    public static void getFilePath(String filePath, String excelName) throws IOException {
        String rootFile = filePath;
        File root = new File(rootFile);
        File[] subFiles = root.listFiles();

        List<String> fileNameList = new LinkedList<>();
        for (File f : subFiles) {
            fileNameList.add(f.getName());
        }

        fileNameList.stream().forEach(item -> {
            readText(filePath + "\\" + item, item);
        });

        // 写入excel
        excelData(allList, filePath, excelName);
    }

    private static void readText(String filePath, String fileName) {
        LinkedHashSet<String> efficientDataList = new LinkedHashSet<>();

        // 数据收集
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            String str = "";
            fis = new FileInputStream(filePath);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            while ((str = br.readLine()) != null) {
                // 排除干扰
                if (!StringUtils.contains(str, "Started") && !StringUtils.contains(str, "Ended") && !StringUtils.contains(str, "Test") && !StringUtils.contains(str, "[")) {
                    for (String item : keywordList) {
                        if (StringUtils.contains(str, item)) {
                            // 数据收集
                            efficientDataList.add(str);
                        }
                    }
                }

            }
            processData(efficientDataList, fileName);// 数据处理和存储
        } catch (Exception e) {
            System.out.println("找不到指定文件" + e);
        } finally {
            try {
                br.close();
                isr.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void excelData(List<TestResultEntity> allList, String filePath, String excelName) throws IOException {
        String fileName = filePath + "\\" + excelName + ".xlsx";
        File testFile = new File(fileName);
        if (!testFile.exists()) {
            testFile.createNewFile();// 能创建多级目录
        }
        // 已经采集成功了
        try {
            // 头的策略
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 10);
            headWriteCellStyle.setWriteFont(headWriteFont);
            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            WriteFont contentWriteFont = new WriteFont();
            // 字体大小
            contentWriteFont.setFontHeightInPoints((short) 40);
            contentWriteCellStyle.setWriteFont(contentWriteFont);
            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
            // 创建文件
            EasyExcel.write(fileName).registerWriteHandler(horizontalCellStyleStrategy).sheet("文件采集数据").doWrite(dataList(allList));
        } catch (Exception e) {
            System.out.println("error-----生成Excel失败!" + e);
        }

    }

    private static List dataList(List<TestResultEntity> allList) {
        List<List<String>> list = new ArrayList<List<String>>();
        allList.stream().forEach(item -> {
            // 没一行数据
            LinkedHashMap<String, LinkedList<ItemResultEntity>> testLineData = item.getTestData();
            testLineData.forEach((k, v) -> {
                List<String> data = new ArrayList<String>();
                data.add(k);// 文件名字
                // 文件数据
                LinkedList<ItemResultEntity> testLineListData = (LinkedList<ItemResultEntity>) v;
                testLineListData.stream().forEach(testItem -> {
                    testItem.getTestName();
                    data.add(testItem.getTestName());
                    data.add(testItem.getTestValue());
                    if (testItem.getTestUnit() != null) {
                        data.add(testItem.getTestUnit());
                    }
                });
                list.add(data);
            });
        });
        return list;
    }

    private static void processData(LinkedHashSet<String> efficientDataList, String fileName) {
        //数据处理
        LinkedList<ItemResultEntity> itemResultEntities = new LinkedList<>();// 共41调数据
        LinkedList<String> tempList = new LinkedList<>();// 所有数据 有脏
        LinkedList<String> finalTempList = tempList;
        efficientDataList.stream().skip(17).forEach(item -> {
            finalTempList.add(item);
            System.out.println("item---" + item);
        });
        LinkedList<String> tempList2 = new LinkedList<>();// 所有数据 有脏
        tempList = finalTempList;
        //        if (tempList.size() == 20) {
        //            efficientDataList.stream().skip(30).forEach(item -> {
        //                tempList2.add(item);
        //            });
        //            tempList.clear();
        //            tempList = tempList2;
        //
        //        }
        HashMap<String, String> lastVdd = new HashMap<>();
        tempList.stream().forEach(s1 -> {
            String item = s1.replaceAll("\\s{1,}", " ");
            for (String keyword : keywordList2) {
                if (StringUtils.contains(s1, keyword)) {
                    String[] s = item.split(" ");
                    ItemResultEntity itemResultEntity = new ItemResultEntity();
                    itemResultEntity.setTestName(s[1]);
                    itemResultEntity.setTestValue(s[3]);
                    itemResultEntities.add(itemResultEntity);
                }
            }
            if (StringUtils.contains(s1, " VDD PASSED ")) {
                lastVdd.put("lastVDD", item);
            }
        });
        if (lastVdd.get("lastVDD") != null) {
            String item = lastVdd.get("lastVDD");
            String[] s = item.split(" ");
            ItemResultEntity itemResultEntity = new ItemResultEntity();
            itemResultEntity.setTestName(s[1]);
            itemResultEntity.setTestValue(s[3]);
            itemResultEntities.add(itemResultEntity);
        }
        TestResultEntity testResultEntity = new TestResultEntity();
        LinkedHashMap<String, LinkedList<ItemResultEntity>> objectObjectLinkedHashMap = new LinkedHashMap<>();
        objectObjectLinkedHashMap.put(fileName, itemResultEntities);
        testResultEntity.setTestData(objectObjectLinkedHashMap);
        allList.add(testResultEntity);
    }
}
